package com.exmaple.springcloud.predicate;

import jakarta.validation.constraints.NotNull;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;


@Component
public class UserLevelRoutePredicateFactory extends AbstractRoutePredicateFactory<UserLevelRoutePredicateFactory.Config> {

    public UserLevelRoutePredicateFactory(){
        super(UserLevelRoutePredicateFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userType");
    }

    @Override
    public Predicate<ServerWebExchange> apply(UserLevelRoutePredicateFactory.Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                //检查request的参数里面，userType是否为指定的值，符合配置就通过
                String userType = serverWebExchange.getRequest().getQueryParams().getFirst("userType");
                if (userType!=null&&userType.equals(config.getUserType())){//如果userType参数存在，就和config的数据进行比较
                    return true;
                }
                return false;
            }

            @Override
            public Object getConfig() {
                return config;
            }

            @Override
            public String toString() {
                return String.format("UserLevel:%s",config.getUserType());
            }
        };
    }

    @Validated
    public static class Config {//路由断言规则的类
        @NotNull
        private String userType; //用户等级

        public void setUserType(String userType) {
            this.userType = userType;
        }

        public String getUserType() {
            return userType;
        }
    }
}